package workers;

import java.beans.PropertyChangeListener;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Logger;

import application.MachineID;
import application.Server;

import protocol.TransferenciaServidorCliente;

public class ClientUploadWorker extends TimedWorker implements Runnable {

	private File fileToUpload=null;
	private MachineID machineID = null;
	
	private TransferenciaServidorCliente transferencia;
	
	public ClientUploadWorker( File fileToUpload, MachineID machineID ,PropertyChangeListener changeListener){
		super( "Enviar archivo " + fileToUpload.getPath() + " a " + machineID.toString() , changeListener);
		this.machineID = machineID;
		this.fileToUpload = fileToUpload;
		transferencia = null;
		setCurrentAction("waiting for turn in poool");

	}
	
	public void cancelTransfer(){
		if(transferencia != null){
			transferencia.setCancelTransfer();
		}
	}

	@Override
	public void run() {
		if( ! isCanceled() ){
			setCurrentAction("running");

			Logger logger = Logger.getLogger( Server.loggerName );
			try {

				
				logger.fine("Client Uploading file.");
				//open and close the socket to generate a process in the server
				Socket s = machineID.createSocket();
				assert s.isConnected();
				
				startWork();

				String archivoDestino = fileToUpload.getName();	

				DataOutputStream flujo=new DataOutputStream(s.getOutputStream());				
				DataInputStream flujoEntrada = new DataInputStream(s.getInputStream());

				BufferedWriter wr = null;
				wr = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
				String command = "Up" + archivoDestino + "\n";
				wr.write(command);
				wr.flush();	

				logger.fine("El Cliente envio el comando al servidor:  " + command);
				setCurrentAction("sending command " + command );
				
				transferencia = new TransferenciaServidorCliente(flujo, flujoEntrada, fileToUpload , this );
				transferencia.run();

				s.shutdownInput();
				s.shutdownOutput();
				s.close();
				//setCurrentAction("socket shut down and closed");
				stopWork();

			} catch (UnknownHostException e) {
				logger.severe( e.getMessage());
				e.printStackTrace();
			} catch (IOException e) {
				logger.severe( e.getMessage());
				e.printStackTrace();
			}
		}
	}

	@Override
	public void cancelTask() {
		if( transferencia != null ) transferencia.setCancelTransfer();
		setCanceled(true);
	}

}
